#include <stdio.h>
#include <stdlib.h>
#include <cstdlib>
#include <cerrno>

#include <string>
#include <cstring>
#include <iostream>

#include "../rapidxml/rapidxml.hpp"
#include "../rapidxml/rapidxml_print.hpp"

#define LINUX_OS

#ifdef LINUX_OS
 #include <netdb.h>
#endif

#ifdef WIN_OS
 #include <Winsock2.h>
#endif


#if IBM
#include <windows.h>
#endif

void parseXML(std::string aXml){
	std::cout << aXml;
    char * cstr;
    rapidxml::xml_document<> doc;
    cstr = new char [aXml.size()+1];
	strcpy (cstr, aXml.c_str());
    doc.parse<0>(cstr);
    rapidxml::xml_node<>* response = doc.first_node();
    std::cout << "node name: " << response->first_node()->name() << "\n";
}


std::string XFSEpost(std::string request) {
	
	const char * r;

	r = request.c_str();
	static const char *BODY = r;
	static const char *HEADERS = "POST http://atilla.hinttech.com/fseconomy/fsagentFSX HTTP/1.0\r\n"
	"Host: atilla.hinttech.com\r\n"
	"Accept: */*\r\n"
	"Connection: keep-alive\r\n"
	"Content-Type: application/x-www-form-urlencoded\r\n"
	"Content-Length: ";

	   struct addrinfo req, *res;
	   memset(&req, 0, sizeof(req));
	   req.ai_family = AF_UNSPEC;
	   req.ai_socktype = SOCK_STREAM;

	   if (getaddrinfo("atilla.hinttech.com", "http", &req, &res) < 0)
	   {
	      perror("getaddrinfo");
	      return "Error: FSE server is offline.";
	   }

	   int s = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
	   if (s < 0)
	   {
	      perror("Error: socket error");
	      return "Error: socket error";
	   }
	   if (connect(s, res->ai_addr, res->ai_addrlen) < 0)
	   {
	      perror("connect");
	      close(s);
	      return "Error: connect error";
	   }

	   char *buffer = (char*)malloc(strlen(BODY) + strlen(HEADERS) + 256);
	   sprintf(buffer, "%s%d\r\n\r\n%s\r\n\r\n", HEADERS, strlen(BODY), BODY);
	   if (send(s, buffer, strlen(buffer), 0) < 0)
	   {
	      perror("send");
	   }
	   else
	   {
	      char recvbuffer[2048] = { 0 };
	      int recvcount = 0;
	      std::string str;
	      recvcount = recv(s, recvbuffer, sizeof(recvbuffer), 0);
	      while (recvcount > 0)
	      {
	    	 str.append(recvbuffer);
	         recvcount = recv(s, recvbuffer, sizeof(recvbuffer), 0);
	      }

	      //std::cout << str.substr(str.find("<"),str.length()) << std::endl;

	      //return str.substr(str.find("<"),str.length());
	      parseXML(str.substr(str.find("<"),str.length()));


	   }
	   free(buffer);
	   close(s);
	   return "ok";

}

void readT () {
	std::string mystr;
	while(1) {
		std::cin >> mystr;
		XFSEpost(mystr);
	}
}

int main () {

	/*XFSEpost("user=stonyo&pass=V9RA4MBS&action=accountCheck");*/
	//XFSEpost("user=stonyo&pass=V9RA4MBS&action=startFlight&lat=5&lon=5&aircraft=Cessna");
	//user=stonyo&pass=V9RA4MBS&action=startFlight&lat=47.2567&lon=0.113611&aircraft=Stinson%20L-5B
	
	readT();
	
	return 0;
}
